package com.hzit.sb2.controller;

import com.hzit.sb2.bean.User;
import com.hzit.sb2.bean.UserItem;
import com.hzit.sb2.bean.weixinEntity.MsgReqBodyEntity;
import com.hzit.sb2.bean.weixinEntity.TxtEntity;
import com.hzit.sb2.mapper.UserMapper;
import com.hzit.sb2.service.IUserService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService userService;

    @GetMapping({"/","/login"})
    public String toLogin(){
        return "login";
    }

    @PostMapping({"/login"})
    public String login( HttpSession session,
                        @RequestParam("username")String username, @RequestParam("pwd")String pwd){
        User user = userService.selectByName(username, pwd);
        if(user!=null){
            session.removeAttribute("msg");
            session.setAttribute("loginUser",username);
            return "redirect:/emp/main";
        }
        session.setAttribute("msg","用户名或密码错误，请重试");
        return "redirect:/user/";
    }

    @GetMapping("/qrcode")
    public String toQrcode(){
        String ticket = "gQHc8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyb3VWZ29NQS1jNDQxNG84T3h2MU0AAgSYDSlfAwSAOgkA";
        return "redirect:https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket;
    }

    @RequestMapping("/list")
    public String userList(Model model){
        Map<String, Object> map = userService.getUserListInfo();
        String qrcode = userService.qrcode();
        model.addAttribute("total",map.get("total"));
        model.addAttribute("count",map.get("count"));
        model.addAttribute("userList",map.get("userList"));
        model.addAttribute("qrcode",qrcode);
        return "list";
    }

    @RequestMapping("/detail")
    @ResponseBody
    public List<Map<String , String >> detail(){
        Map<String, Object> map = userService.getUserListInfo();
        List<Map<String , String>> userList = (List<Map<String, String>>) map.get("userList");
        return userList;
    }
    @GetMapping("/toMsg")
    public String toMsg(@RequestParam("openid") String openid, Model model){
        model.addAttribute("openid",openid);
        return "message";
    }
    @PostMapping("/sendMsg")
    public String sendMsg(MsgReqBodyEntity msg, TxtEntity txt){
        Boolean flag = userService.sendMsg(msg,txt);
        return "redirect:/user/list";
    }

    @RequestMapping("/findByOpenId")
    @ResponseBody
    public Map<String,Object> findById(@RequestParam("openid")String openid){
        Map<String,Object> map =  userService.findById(openid);
        return map;
    }
}
